package com.gzc.just.play.last.war.allinone.orchestration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 服务器编排器
 * 实现SmartLifecycle接口，控制所有服务器的启动顺序和生命周期
 */
@Component("serverOrchestrator")
public class ServerOrchestrator implements SmartLifecycle {
    
    private static final Logger logger = LoggerFactory.getLogger(ServerOrchestrator.class);
    
    @Autowired
    private ServerDependencyGraph dependencyGraph;
    
    @Autowired
    private ServerStateManager stateManager;
    
    @Autowired
    private ServerHealthChecker healthChecker;
    
    @Autowired
    private ServerStartupCoordinator startupCoordinator;
    
    private boolean isRunning = false;
    private CountDownLatch startupLatch;
    
    @Override
    public void start() {
        logger.info("Starting server orchestrator...");
        
        try {
            // 设置启动状态
            isRunning = true;
            startupLatch = new CountDownLatch(1);
            
            // 启动状态管理器
            stateManager.initialize();
            
            // 启动健康检查器
            healthChecker.start();
            
            // 按依赖顺序启动服务器
            startupCoordinator.startServersInOrder();
            
            logger.info("Server orchestrator started successfully");
            startupLatch.countDown();
            
        } catch (Exception e) {
            logger.error("Failed to start server orchestrator", e);
            isRunning = false;
            if (startupLatch != null) {
                startupLatch.countDown();
            }
            throw new RuntimeException("Failed to start server orchestrator", e);
        }
    }
    
    @Override
    public void stop() {
        logger.info("Stopping server orchestrator...");
        
        try {
            isRunning = false;
            
            // 停止健康检查器
            healthChecker.stop();
            
            // 停止所有服务器
            stateManager.stopAllServers();
            
            logger.info("Server orchestrator stopped successfully");
            
        } catch (Exception e) {
            logger.error("Error while stopping server orchestrator", e);
        }
    }
    
    @Override
    public boolean isRunning() {
        return isRunning;
    }
    
    /**
     * 等待所有服务器启动完成
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return 是否成功启动
     */
    public boolean waitForStartup(long timeout, TimeUnit unit) {
        if (startupLatch == null) {
            return false;
        }
        
        try {
            return startupLatch.await(timeout, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.warn("Interrupted while waiting for startup", e);
            return false;
        }
    }
    
    /**
     * 获取服务器状态
     * @return 服务器状态映射
     */
    public Map<String, ServerState> getServerStates() {
        return stateManager.getAllServerStates();
    }
    
    /**
     * 获取依赖关系图
     * @return 依赖关系图
     */
    public ServerDependencyGraph getDependencyGraph() {
        return dependencyGraph;
    }
    
    /**
     * 检查所有服务器是否已准备就绪
     * @return 是否准备就绪
     */
    public boolean isAllServersReady() {
        Map<String, ServerState> states = stateManager.getAllServerStates();
        return states.values().stream()
                .allMatch(state -> state == ServerState.READY || state == ServerState.CONNECTED);
    }
}